/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.netcracker.test.eleven;

import java.util.Arrays;
import java.util.concurrent.RecursiveTask;

/**
 *
 * @author I
 */
public class MergeSortForkJoin extends RecursiveTask<int[]>{
    int[]a;
    public MergeSortForkJoin(int[] a){
        this.a=a;
    }
    
     public static int[] merge (int[] mass1, int[] mass2) { 
          int a = 0, b = 0;
          int[] merged = new int[mass1.length + mass2.length];
          for (int i = 0; i < mass1.length + mass2.length; i++){
                if (b < mass2.length && a < mass1.length)
                    if (mass1[a] > mass2[b] && b < mass2.length)
                       merged[i] = mass2[b++];
                    else
                       merged[i] = mass1[a++];
                else
                    if (b < mass2.length)
                        merged[i] = mass2[b++];
                    else
                        merged[i] = mass1[a++];
            }
            return merged;
     } 
    @Override
    protected int[] compute() {
         if ( a.length==1 ) return a; 
         int m = (a.length)/2;
         int[] a1 = Arrays.copyOfRange(a, 0, m);
         int[] a2 = Arrays.copyOfRange(a, m, a.length);
         MergeSortForkJoin mgfj1 = new MergeSortForkJoin(a1);
         MergeSortForkJoin mgfj2 = new MergeSortForkJoin(a2);
         mgfj1.fork();
         mgfj2.fork();
         
         return merge(mgfj1.join(), mgfj2.join());
         
         
    }
    
}
